package com.web.dwm;

import com.entity.CatPost;
import com.entity.PageManager;
import com.entity.User;
import com.entity.Varietiess;
import com.service.dwm.CatPostService;
import com.service.dwm.VarietiesService;
import com.utils.EncryptCodeUtils;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/varieties")
@MultipartConfig
public class VarietiesServlet extends HttpServlet {

    //用户的逻辑层
    private VarietiesService varietiesService = new VarietiesService();
    private CatPostService catPostService = new CatPostService();

    //request对象
    private HttpServletRequest request;
    //response对象
    private HttpServletResponse response;

    //不管是post还是get请求，都会进入到service
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        synchronized (this) {
            //初始化请求和响应
            this.request = request;
            this.response = response;
            String method = request.getParameter("method");
            switch (method) {
                case "index": queryVarietiess(); break;
                case "del": delUser(); break;
                case "toAddPage": toAddPage(); break;
                case "add": addUser(); break;
                case "showPic": showPic(); break;
                case "update": update(); break;
                case "queryUser": queryUser(); break;
                case "toIndex": toIndex(); break;
                case "details": details(); break;
                case "price": price();break;
            }
        }

    }

    private void price() throws ServletException, IOException {
        String catbreed = request.getParameter("catbreed");
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        pm.setRn(20);
        int totalCount=0;
        if ("".equals(catbreed)){
            totalCount = catPostService.queryCatPostTotalCountT("布偶猫");
        }else{
            totalCount = catPostService.queryCatPostTotalCountT(catbreed);
        }
        System.out.println(totalCount);
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数
        List<CatPost> catPosts = new ArrayList<>();
        if ("".equals(catbreed)){
            catPosts = varietiesService.queryCatPosts("布偶猫",pm);
            catbreed = "布偶猫";
        }else{
            catPosts = varietiesService.queryCatPosts(catbreed,pm);
        }
        request.setAttribute("catPosts", catPosts);
        request.setAttribute("pm", pm);
        request.setAttribute("catbreed", catbreed);
        List<Varietiess> varietiesses = varietiesService.queryVarietiess();
        request.setAttribute("varietiesses", varietiesses);
        WebUtils.toRequestPageVarietiess(request, response, "price");
    }

    private void details() throws ServletException, IOException {
        String varieties = (String)request.getParameter("varieties");
        Varietiess varietiess = varietiesService.queryVarieties(varieties);
        request.setAttribute("varieties", varietiess);

        WebUtils.toRequestPageVarietiess(request, response, "varieties");
    }

    private void toIndex() throws ServletException, IOException {
        List<Varietiess> varieties = varietiesService.queryVarietiess();
        request.setAttribute("varieties", varieties);
        WebUtils.toRequestPageVarietiess(request, response, "catBreed");

    }

    private void queryUser() throws ServletException, IOException {

        String varieties = request.getParameter("varieties");
        Varietiess varietiess = varietiesService.queryVarieties(varieties);
        request.setAttribute("varietiess", varietiess);
        request.setAttribute("outerLi", "varieties");
        request.setAttribute("innerLi", "showVarieties");
        WebUtils.toRequestPageVarieties(request, response, "updateVarieties");
    }

    private void update() throws IOException, ServletException {
        Varietiess varietiess = WebUtils.getBean(Varietiess.class, request);
        String path1 = WebUtils.uploadFile(request, "newPic1", WebUtils.SAVE_PATH);
        //如果path是空，新的图片没上传，不做修改
        varietiess.setPic1(path1==null?varietiess.getPic1():path1);
        String path2 = WebUtils.uploadFile(request, "newPic2", WebUtils.SAVE_PATH);
        //如果path是空，新的图片没上传，不做修改
        varietiess.setPic2(path2==null?varietiess.getPic2():path2);
        String path3 = WebUtils.uploadFile(request, "newPic3", WebUtils.SAVE_PATH);
        //如果path是空，新的图片没上传，不做修改
        varietiess.setPic3(path3==null?varietiess.getPic3():path3);
        String path4 = WebUtils.uploadFile(request, "newPic4", WebUtils.SAVE_PATH);
        //如果path是空，新的图片没上传，不做修改
        varietiess.setPic4(path4==null?varietiess.getPic4():path4);
        //修改
        boolean result = varietiesService.updateVarieyies(varietiess);
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        request.getSession().setAttribute("msg", result?"修改成功":"修改失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("varieties?method=index&pn="+(pm==null?"":pm.getPn()));
    }

    private void showPic() throws IOException {
        String pic = request.getParameter("pic");
        File file = new File(pic);
        //将图片的字节写入到页面
        //jsp中的out写入东西
        OutputStream out = response.getOutputStream();
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
        response.flushBuffer();//刷新缓存
    }

    private void addUser() throws IOException, ServletException {
        //转化为实体类
        Varietiess varietiess = WebUtils.getBean(Varietiess.class, request);

        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()+1);
            pm.setPages();
        }

        //重新设置文件路径
        varietiess.setPic1(WebUtils.uploadFile(request, "pic1", WebUtils.SAVE_PATH));
        varietiess.setPic2(WebUtils.uploadFile(request, "pic2", WebUtils.SAVE_PATH));
        varietiess.setPic3(WebUtils.uploadFile(request, "pic3", WebUtils.SAVE_PATH));
        varietiess.setPic4(WebUtils.uploadFile(request, "pic4", WebUtils.SAVE_PATH));
        boolean result = varietiesService.addVarieties(varietiess);
        request.getSession().setAttribute("msg", result?"增加成功":"增加失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("varieties?method=index&pn="+(pm==null?"":pm.getPages()));
    }

    private void toAddPage() throws ServletException, IOException {
        request.setAttribute("outerLi", "varieties");
        request.setAttribute("innerLi", "showVarieties");
        WebUtils.toRequestPageVarieties(request, response, "addVarieties");
    }

    private void delUser() throws IOException {
        String varieties = request.getParameter("varieties");
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()-1);
            pm.setPages();
            //删除之后，正好最后一页没了，直接使用最后一页当作当前页
            pm.setPn(pm.getPn()>=pm.getPages()?pm.getPages():pm.getPn());
        }
        boolean result = varietiesService.delVarieties(varieties);
        request.getSession().setAttribute("msg", result?"删除成功":"删除失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("varieties?method=index&pn="+((pm==null)?"":pm.getPn()));
    }


    private void queryVarietiess() throws ServletException, IOException {
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        List<Varietiess> varieties = varietiesService.queryVarieties(pm);
        int totalCount = varietiesService.queryVarietiesTotalCount();
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数

        request.setAttribute("varieties", varieties);
        request.getSession().setAttribute("pm", pm);
        request.setAttribute("outerLi", "varieties");
        request.setAttribute("innerLi", "showVarieties");
        WebUtils.toRequestPageVarieties(request, response, "showVarieties");
    }

}
